import React, { Fragment, useState, useEffect } from 'react';
import type { FC } from 'react';
import 'github-markdown-css'; // 引入github的markdown主题样式
import MarkdownIt from 'markdown-it';
import 'react-markdown-editor-lite/lib/index.css';
import MdEditor from 'react-markdown-editor-lite';

import { useRequest, useHistory } from 'umi';
import hljs from 'highlight.js'; // 引入highlight.js库
import 'highlight.js/styles/github.css'; // 引入github风格的代码高亮样式
// import 'highlight.js/styles/dark.css'
import style from './index.less';
import { Button, Input, Drawer, Form, Select, Tag, Upload, message, Modal } from 'antd';
import {
  saveArticle,
  ArticleType,
  ArticleColumn,
  UploadImage,
  createArticleColumn
} from './service';
import { SubmitParams, ArticleTypeObj, ColumnObj } from './type';
import { TagsFilled, LoadingOutlined, PlusOutlined } from '@ant-design/icons';

/**
 *  组件外声明只加载一次
 * */
// 声明antdesign组件
const { TextArea } = Input;
const { CheckableTag } = Tag;
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

// 声明Markdown组件
const mdParser = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true, // 设置代码高亮的配置
  highlight(code, language) {
    if (language && hljs.getLanguage(language)) {
      try {
        return `<pre><code class="hljs language-${language}">${
          hljs.highlight(code, { language }).value
        }</code></pre>`;
      } catch (__) {}
    }

    return `<pre class="hljs"><code>${mdParser.utils.escapeHtml(code)}</code></pre>`;
  },
});
async function handleImageUpload(file, callback) {
  const formData = new FormData();
  formData.append('file', file);
  await UploadImage(formData).then(res => {
    callback(res.url);
  });
  const reader = new FileReader();

  reader.readAsDataURL(file);
}
const MarkDown: FC<Record<string, any>> = () => {
  const history = useHistory();
  /**
   *    MarkDown 部分
   *
   */
  // Markdown文本
  const [text, setText] = useState();
  // MarkDown HTML
  const [html, setHtml] = useState();
  // 文本编辑器内容变化
  const handleEditorChange = ({ html, text }) => {
    setText(text);
    setHtml(html);
    const reg = /<[^<>]+>/g; // 1、全局匹配g肯定忘记写  2、<>标签中不能包含标签实现过滤HTML标签
    const text2 = html.replace(reg, '').replace(/[\r\n]/g, '');

    setSubmitParams({ ...submitParams, html, desc: text2.slice(0, 100) });
  };

  /**
   * 抽屉部分
   *
   */
  // 抽屉显示
  const [visible, setVisible] = useState(false);
  // 标签
  const [tags, setTags] = useState<ArticleTypeObj[]>([]);
  // 专栏
  const [articleColumn, setArticleColumn] = useState<ColumnObj[]>([]);
  // 抽屉是否展开
  const showDrawer = () => {
    setVisible(true);
    // 请求文章专栏接口 param:user_id
    const user_id = localStorage.getItem('user_id');
    ArticleColumn(Number(user_id)).then(res => {
      setArticleColumn(res.data);
    });
    // 请求文章分类接口
    ArticleType().then(res => {
      const tempData = res.data;
      tempData.map((data: ArticleTypeObj, index: number) => (data.checked = false));
      setTags(tempData);
    });
  };
  // 关闭抽屉
  const onClose = () => {
    setVisible(false);
  };
  //  选中分类Tag
  const handleChangeTag = (tagId: number, checked: any, tagType: string) => {
    const tempTags = tags;
    tempTags.map((tag, index) => (tag.id == tagId ? (tag.checked = true) : (tag.checked = false)));
    setTags([...tempTags]);
    setSubmitParams({ ...submitParams, type: tagType });
  };

  /**
   *  上传图片
   */
  // 图片地址
  const [imageUrl, setImageUrl] = useState<string>();
  // 加载
  const [loading, setLoading] = useState(false);
  // 上传前
  const beforeUpload = file => {
    // 图片格式
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  // 转为base64
  const getBase64 = (img: Blob, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  // 上传图片
  const handleChange = (info: any) => {
    console.log(info.file, 'info');
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (imageUrl: any) => {
        setImageUrl(imageUrl);
        setSubmitParams({ ...submitParams, cover: info.file.response.url });
        setLoading(false);
      });
    }
  };

  /**
   *   最后提交内容
   *
   */
  // 提交参数
  const [submitParams, setSubmitParams] = useState<SubmitParams>({
    html: '',
    markedown: '',
    user_id: localStorage.getItem('user_id') || '',
    desc: '',
    title: '',
    username: localStorage.getItem('username') || '',
    date: new Date(),
    type: '',
    column: '',
    cover: '',
  });

  // 提交
  const Submit = publish => {
    const param = { ...submitParams, publish };
    saveArticle(param).then(res => {
      if (res.data == 'success') {
        message.success('发布成功');
        setVisible(false);
        history.push('/client/index');
      } else {
        message.error('提交失败');
      }
      setVisible(false);
    });
  };
  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };
  const [columnsParam, setColumnsParam] = useState({
    username: localStorage.getItem('username') || '',
    user_id: localStorage.getItem('user_id') || '',
    column: '',
    column_detail: '',
  });
  // 添加专栏
  const handleOk = async () => {
    const { code } = await createArticleColumn(columnsParam);
    if (code === 1000) {
      message.success('请等待管理员审核');
      setIsModalVisible(false);
    } else {
      message.error('失败');
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  useEffect(() => {}, []);
  return (
    <div className={style.markdown}>
      <div className={style.header}>
        {/* onChange(e)   e.target.value */}
        <Input
          className={style.input}
          size="middle"
          onChange={e => setSubmitParams({ ...submitParams, title: e.target.value })}
        />
        <div className={style.btn_con}>
          <Button type="primary" onClick={showDrawer}>
            发布
          </Button>
        </div>
      </div>
      <MdEditor
        value={text}
        style={{ height: '500px' }}
        // 用于右边展示效果的渲染
        renderHTML={text => mdParser.render(text)}
        onChange={handleEditorChange}
        onImageUpload={handleImageUpload}
        config={{
          view: {
            menu: true,
            md: true,
            html: true,
          },
          imageUrl: 'https://octodex.github.com/images/minion.png',
        }}
      />
      <Drawer
        title="发布文章"
        placement="right"
        onClose={onClose}
        visible={visible}
        width={500}
        footer={(
          <>
            <Button type="default" onClick={onClose} className={style.btn}>
              取消
            </Button>
            <Button
              type="primary"
              ghost
              onClick={() => {
                Submit(0);
              }}
              className={style.btn}
            >
              保存草稿
            </Button>
            <Button
              type="primary"
              onClick={() => {
                setSubmitParams({ ...submitParams, publish: 1 });
                Submit(1);
              }}
            >
              确认并发布
            </Button>
          </>
        )}
      >
        <Form {...layout} name="nest-messages">
          <Form.Item label="分类" required>
            {tags &&
              tags.map((item, index) => (
                <CheckableTag
                  key={index}
                  checked={item.checked}
                  onChange={checked => handleChangeTag(item.id, checked, item.type)}
                >
                  {item.type}
                </CheckableTag>
              ))}
          </Form.Item>
          <Form.Item label="收录至专栏">
            <div style={{ display: 'flex' }}>
              <Select
                onChange={e => {
                  setSubmitParams({ ...submitParams, column: e });
                }}
                style={{ marginRight: '4px' }}
              >
                {articleColumn.map((item, index) => (
                  <Select.Option value={item.column}>{item.column}</Select.Option>
                ))}
              </Select>
              <Button type="primary" shape="circle" icon={<PlusOutlined />} onClick={showModal} />
            </div>
          </Form.Item>
          <Form.Item label="文章封面">
            <Upload
              // 对应后端的 ctx.request.files.file
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/api/client/Upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%', marginTop: '10px' }} />
              ) : (
                <div>
                  {loading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              )}
            </Upload>
          </Form.Item>
          <Form.Item label="文章简述">
            <Input.TextArea
              showCount
              maxLength={100}
              rows={4}
              value={submitParams.desc}
              onChange={e => {
                console.log(e.target.value);
                setSubmitParams({ ...submitParams, desc: e.target.value });
              }}
            />
          </Form.Item>
        </Form>
      </Drawer>
      <Modal title="添加专栏" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <div className={style.modal_label}>
          <span style={{ color: 'red' }}>*</span> 专栏名称
        </div>

        <Input
          placeholder="请输入专栏名称"
          onChange={e => {
            setColumnsParam({ ...columnsParam, column: e.target.value });
          }}
        />
        <div className={style.modal_label}>
          <span style={{ color: 'red' }}>*</span> 专栏描述
        </div>
        <TextArea
          rows={4}
          placeholder="请输入专栏描述"
          maxLength={20}
          onChange={e => {
            setColumnsParam({ ...columnsParam, column_detail: e.target.value });
          }}
        />
      </Modal>
    </div>
  );
};

export default MarkDown;
